// UDPClient.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	WSADATA wsaData;
	WORD wVersion = MAKEWORD(2, 2);
	// WSA Startup
	if (WSAStartup(wVersion, &wsaData))
	{
		cout << "WSA Startup error: " << WSAGetLastError() << endl;
	}
	else
	{
		cout << "WSA Startup success" << endl;
	}

	// Socket/WSASocket
	SOCKET sender;
	sender = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	cout << "Socket created" << endl;

	// xac dinh dia chi, phan giai ten mien
	SOCKADDR_IN serverAddress;
	serverAddress.sin_family = AF_INET;
	serverAddress.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
	serverAddress.sin_port = htons(8888);
	cout << "Server address created" << endl;

	// send to
	char *senderBuf = "Xin chao Viet Nam";
	int senderBufLen = strlen(senderBuf);
	int senderFlags = 0;
	int sentBytes = sendto(sender, senderBuf, senderBufLen, senderFlags, (SOCKADDR*)&serverAddress, sizeof(serverAddress));
	if (sentBytes == SOCKET_ERROR)
	{
		cout << "Send bytes error: " << WSAGetLastError() << endl;
	}
	else
	{
		cout << "Sent success: " << sentBytes << " bytes" << endl;
		cout << senderBuf << endl;
	}

	// close socket
	if (closesocket(sender))
	{
		cout << "Socket close error: " << WSAGetLastError() << endl;
	}
	else
	{
		cout << "Socket closed" << endl;
	}


	// WSA Cleanup
	if (WSACleanup())
	{
		cout << "WSA Cleanup error: " << WSAGetLastError() << endl;
	}
	else
	{
		cout << "WSA Cleanup success" << endl;
	}
	return 0;
}

